<?php

namespace App\Http\Controllers\Api;

use App\Models\Visitor;
use EasyWeChat\Factory;
use Illuminate\Http\Request;

class VisitorController extends BaseController
{
    /**
     * 小程序登录
     */
    public function login(Request $request) {
        try{
            $code = $request->input('code', '');
            if (empty($code)) return $this->response(400, 'code参数错误');
            $config = config('wechat.mini');
            $app = Factory::miniProgram($config);
            $result = $app->auth->session($code);
            if (!isset($result['openid'])) return $this->response(400, '获取用户openid失败');
            $visitor = Visitor::where('openid', $result['openid'])->first();
            if (empty($visitor)) {
                $data = [
                    'openid' => $result['openid']
                ];
                if (!Visitor::create($data)) return $this->response(400, '创建用户失败');
                $is_perfect = 0;
            } else {
                $is_perfect = 1;
                if (empty($visitor->name)) $is_perfect = 0;
            }
            return $this->response(200, '登录成功', ['openid' => $result['openid'], 'is_perfect' => $is_perfect]);
        }catch (\Throwable $e) {
            return $this->response(500, $e->getMessage());
        }
    }

    /**
     * 完善信息
     */
    public function perfect(Request $request) {
        try{
            $name = $request->input('name', '');
            if (empty($name)) return $this->response(400, '请填写真实姓名');
            $mobile = $request->input('mobile', '');
            if (empty($mobile)) return $this->response(400, '请填写手机号码');
            $data = [
                'name' => $name,
                'mobile' => $mobile
            ];
            if (!Visitor::where('id', $request->visitor->id)->update($data)) {
                return $this->response(400, '完善信息失败');
            }
            return $this->response(200, '操作成功');
        }catch (\Throwable $e) {
            return $this->response(500, $e->getMessage());
        }
    }
    /**
     * 个人信息
     */
    public function info(Request $request) {
        try{
            return $this->response(200, '操作成功', $request->visitor);
        }catch (\Throwable $e) {
            return $this->response(500, $e->getMessage());
        }
    }
}
